'use client'

import { useState, useEffect } from 'react'
import { useFieldArray, useForm } from 'react-hook-form'
import { useRouter } from 'next/navigation'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { CirclePlus, CircleMinus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { useToast } from '@/components/ui/use-toast'
import useRequest from '@/utils/request'
import { useDispatch, useSelector } from 'react-redux'
import { selectCurProject } from '@/store/project-slice'
import { selectConfig, setConfig } from '@/store/config-slice'
import UpgradeDialog from '@/components/UpgradeDialog'

const KeywordSchema = z.object({
  keyword: z
    .string()
    .min(3, {
      message: 'Please enter a reasonable keyword (between 3 and 50 characters).',
    })
    .max(50, {
      message: 'Please enter a reasonable keyword (between 3 and 50 characters).',
    }),
})

const FormSchema = z.object({
  keywords: z.array(KeywordSchema).min(1, {
    message: `You need to add at least one keyword`,
  }),
})

export default function KeywordsAdd() {
  const router = useRouter()
  const { toast } = useToast()
  const [project, setProject] = useState(null)
  const [recommendKeywords, setRecommendKeywords] = useState([])
  const curProject = useSelector(selectCurProject)
  const request = useRequest()
  const dispatch = useDispatch()
  const [open, setOpen] = useState(false)
  const config = useSelector(selectConfig)

  useEffect(() => {
    setRecommendKeywords(project?.recommend_keywords.split(', '))
  }, [project])

  const fetchData = async () => {
    if (!curProject) {
      return
    }
    const res = await request.get(`red_growth/project?id=${curProject.id}`)
    setProject(res.data)
  }

  useEffect(() => {
    fetchData()
  }, [curProject])

  const form = useForm({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      keywords: [
        {
          keyword: '',
        },
      ],
    },
  })

  async function onSubmit(data) {
    if (config.keyword <= 0) {
      setOpen(true)
      return
    }

    const keywordsArr = []
    data.keywords.forEach(item => {
      keywordsArr.push(item.keyword)
    })

    try {
      await request.post('red_growth/batch_add_keyword', { keyword: keywordsArr.join(','), project_id: curProject.id })
      toast({
        title: `Keyword '${keywordsArr.join(',')}' has been added.`,
        description: 'It may take up to 10 minutes for changes to become active.',
      })
      router.push('/mentions')

      const configRes = await request.get('account/config')
      dispatch(setConfig(configRes.data))
    } catch (error) {
      console.error('Error submitting form:', error)
    }
  }

  const selectOneKeyword = keyword => {
    // const cur = form.getValues('keyword')
    // if (cur === '') {
    //   form.setValue('keyword', `${keyword}`)
    // } else {
    //   form.setValue('keyword', `${cur},${keyword}`)
    // }
    setKeywords([...keywords, { value: '' }])

    append({ keyword })
  }

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = form

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'keywords',
  })

  return (
    <>
      <UpgradeDialog open={open} setOpen={setOpen} title={'project'} />
      <Form {...form}>
        <form onSubmit={handleSubmit(onSubmit)} className="w-2/3 space-y-6">
          <FormLabel>Recommend Keywords:</FormLabel>

          <ul className="list-disc pl-4">
            {recommendKeywords?.map((item, index) => {
              return (
                <li key={index}>
                  <div className="flex items-center">
                    <div>{item}</div>
                    <CirclePlus
                      className="ml-2 text-primary w-4 cursor-pointer"
                      onClick={() => {
                        append({ keyword: item })
                        console.log(recommendKeywords)
                        setRecommendKeywords(recommendKeywords.filter((x, i) => i !== index))
                      }}
                    />
                  </div>
                </li>
              )
            })}
          </ul>

          {fields.map((item, index) => (
            <FormField
              key={item.id}
              control={control}
              name={`keywords.${index}.keyword`}
              render={({ field }) => (
                <FormItem>
                  {index === 0 && <FormLabel>Keyword to monitor:</FormLabel>}
                  {index === 0 && (
                    <FormDescription>
                      Enter only one keyword or phrase at a time. Any symbols or spaces will be matched literally.
                    </FormDescription>
                  )}
                  <FormControl>
                    <div className="flex items-center">
                      <Input placeholder="ex: Use AI to" {...field} />
                      <CircleMinus className="ml-2 text-primary w-4 cursor-pointer" onClick={() => remove(index)} />
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          ))}

          <Button type="submit">Save</Button>
        </form>
      </Form>
    </>
  )
}
